package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.item.service.LockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lhh
 * @ClassName LockServiceImpl
 * @date 2022 2022/12/8
 */
@Service
public class LockServiceImpl implements LockService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public String lock() throws InterruptedException {
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        while (!redisTemplate.opsForValue().setIfAbsent("lock", s,10,TimeUnit.SECONDS)){
            System.out.println("加锁失败");
            TimeUnit.MILLISECONDS.sleep(10);
        }

        return s;
    }

    @Override
    public void unlock(String uuid) {
        String lock = redisTemplate.opsForValue().get("lock");
        if(lock.equalsIgnoreCase(uuid)){
            redisTemplate.delete("lock");
        }

        //删除=获取值+删除锁  原子操作
        //lua脚本
        String script="if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
    }
}
